<?php

class KreditorPartPayment extends PaymentModule
{
	private	$_html = '';
	private $_postErrors = array();

	public function __construct()
	{
		$this->name = 'kreditorpartpayment';
		$this->tab = 'Payment';
		$this->version = '1.2.2';

		
		$this->currencies = true;
		$this->currencies_mode = 'radio';

        parent::__construct();

        /* The parent construct is required for translations */
		$this->page = basename(__FILE__, '.php');
        $this->displayName = $this->l('Klarna part payment');
        $this->description = $this->l('Accepts payments by Klarna');
		$this->confirmUninstall = $this->l('Are you sure you want to delete your details ?');
	}

	public function install()
	{
		
		if (!parent::install() 
			OR !Configuration::updateValue('KREDITOR_PP_ENABLED', 1)
			OR !Configuration::updateValue('KREDITOR_PP_TESTFLAG', 1)
			OR !Configuration::updateValue('KREDITOR_PP_MERCHANT_ID', '0')
			OR !Configuration::updateValue('KREDITOR_PP_SECRET', '')
			OR !Configuration::updateValue('KREDITOR_PP_PRE_POPULATE', 1)
			OR !Configuration::updateValue('KREDITOR_PP_ORDER_LIMIT', 50000)
			/* Customer currency is default currency */ 
			OR !Db::getInstance()->Execute('UPDATE `'._DB_PREFIX_.'module_currency` SET id_currency=-1 WHERE id_module='.intval($this->id))
			OR !$this->registerHook('payment'))
			return false;
		return true;
	}

	public function uninstall()
	{
		if (!Configuration::deleteByName('KREDITOR_PP_ENABLED')
			OR !Configuration::deleteByName('KREDITOR_PP_TESTFLAG') 
			OR !Configuration::deleteByName('KREDITOR_PP_MERCHANT_ID')
			OR !Configuration::deleteByName('KREDITOR_PP_SECRET')
			OR !Configuration::deleteByName('KREDITOR_PP_PRE_POPULATE')
			OR !Configuration::deleteByName('KREDITOR_PP_ORDER_LIMIT') 
			OR !parent::uninstall())
			return false;
				
	 	return true;
	}

	public function getContent()
	{
		include "kreditor/kreditor.php";
		$this->_html = '<h2>Klarna Partpayment</h2>';
		if (isset($_POST['submitKreditor']))
		{
			if (empty($_POST['merchantid']))
				$this->_postErrors[] = $this->l('Klarna Merchant ID is required.');
			if (empty($_POST['secret']))
				$this->_postErrors[] = $this->l('Klarna shared secret is required.');
			if (empty($_POST['orderlimit']))
				$this->_postErrors[] = $this->l('Klarna order limit is required.');
			if (!isset($_POST['enabled']))
				$_POST['enabled'] = 1;
			if (!isset($_POST['prepopulate']))
				$_POST['prepopulate'] = 1;
				
			if (!sizeof($this->_postErrors))
			{
				Configuration::updateValue('KREDITOR_PP_ENABLED', intval($_POST['enabled']));
				Configuration::updateValue('KREDITOR_PP_TESTFLAG', intval($_POST['testflag']));
				Configuration::updateValue('KREDITOR_PP_MERCHANT_ID', $_POST['merchantid']);
				Configuration::updateValue('KREDITOR_PP_SECRET', $_POST['secret']);
				Configuration::updateValue('KREDITOR_PP_PRE_POPULATE', intval($_POST['prepopulate']));
				Configuration::updateValue('KREDITOR_PP_ORDER_LIMIT', intval($_POST['orderlimit'])); 
				Configuration::updateValue('KREDITOR_PP_COUNTRIES', implode(',', $_POST['countries']));
				create_pclasses_file($_POST['merchantid'], $_POST['secret']);
				$this->displayConf();
			}
			else
				$this->displayErrors();
		}

		$this->displayKreditorPartPayment();
		$this->displayFormSettings();
		return $this->_html;
	}

	public function displayConf()
	{
		$this->_html .= '
		<div class="conf confirm">
			<img src="../img/admin/ok.gif" alt="'.$this->l('Confirmation').'" />
			'.$this->l('Settings updated').'
		</div>';
	}

	public function displayErrors()
	{
		$nbErrors = sizeof($this->_postErrors);
		$this->_html .= '
		<div class="alert error">
			<h3>'.($nbErrors > 1 ? $this->l('There are') : $this->l('There is')).' '.$nbErrors.' '.($nbErrors > 1 ? $this->l('errors') : $this->l('error')).'</h3>
			<ol>';
		foreach ($this->_postErrors AS $error)
			$this->_html .= '<li>'.$error.'</li>';
		$this->_html .= '
			</ol>
		</div>';
	}
	
	
	public function displayKreditorPartPayment()
	{
		$this->_html .= '
		<img src="../modules/kreditorpartpayment/klarna.gif" style="float:left; margin-right:15px;" />
		<b>'.$this->l('This module allows you to accept part payments by Klarna.').'</b><br /><br />
		'.$this->l('You need to configure your kreditor account first before using this module.').'
		<br /><br /><br />';
	}

	public function displayFormSettings()
	{
		$conf = Configuration::getMultiple(array('KREDITOR_PP_ENABLED',
			'KREDITOR_PP_TESTFLAG', 
			'KREDITOR_PP_MERCHANT_ID',
			'KREDITOR_PP_SECRET',
			'KREDITOR_PP_AUTO_ACTIVATE',
			'KREDITOR_PP_AUTO_ACTIVATE_DELAY',
			'KREDITOR_PP_PRE_POPULATE',
			'KREDITOR_PP_ORDER_LIMIT',
			'KREDITOR_PP_COUNTRIES'
			));
			 		
		$enabled 	= array_key_exists('enabled', $_POST) ? $_POST['enabled'] 		: (array_key_exists('KREDITOR_PP_ENABLED', $conf) ? $conf['KREDITOR_PP_ENABLED'] : '');
		$testflag   = array_key_exists('testflag', $_POST) ? $_POST['testflag'] 	: (array_key_exists('KREDITOR_PP_TESTFLAG', $conf) ? $conf['KREDITOR_PP_TESTFLAG'] : '');
		$merchantid = array_key_exists('merchantid', $_POST) ? $_POST['merchantid'] : (array_key_exists('KREDITOR_PP_MERCHANT_ID', $conf) ? $conf['KREDITOR_PP_MERCHANT_ID'] : '');
		$secret 	= array_key_exists('secret', $_POST) ? $_POST['secret'] 		: (array_key_exists('KREDITOR_PP_SECRET', $conf) ? $conf['KREDITOR_PP_SECRET'] : '');
		$autoactivate = array_key_exists('autoactivate', $_POST) ? $_POST['autoactivate'] : (array_key_exists('KREDITOR_PP_AUTO_ACTIVATE', $conf) ? $conf['KREDITOR_PP_AUTO_ACTIVATE'] : '');
		$senddelay 	= array_key_exists('senddelay', $_POST) ? $_POST['senddelay'] 	: (array_key_exists('KREDITOR_PP_AUTO_ACTIVATE_DELAY', $conf) ? $conf['KREDITOR_PP_AUTO_ACTIVATE_DELAY'] : '');
		$prepopulate = array_key_exists('prepopulate', $_POST) ? $_POST['prepopulate'] : (array_key_exists('KREDITOR_PP_PRE_POPULATE', $conf) ? $conf['KREDITOR_PP_PRE_POPULATE'] : '');
		$orderlimit = array_key_exists('orderlimit', $_POST) ? $_POST['orderlimit'] : (array_key_exists('KREDITOR_PP_ORDER_LIMIT',  $conf) ? $conf['KREDITOR_PP_ORDER_LIMIT'] : '');
		$countries = array_key_exists('countries', $_POST) ? $_POST['countries'] : (array_key_exists('KREDITOR_PP_COUNTRIES', $conf) ? $conf['KREDITOR_PP_COUNTRIES'] : '');
		
		if(is_array($countries))
			$countries = implode(",", $countries);
		
		$this->_html .= '
		<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
		<fieldset>
			<legend><img src="../img/admin/contact.gif" />'.$this->l('Settings').'</legend>
			<label>'.$this->l('Enable Kreditor Module').'</label>
			<div class="margin-form">
				<input type="radio" name="enabled" value="1" '.($enabled ? 'checked="checked"' : '').' /> '.$this->l('Yes').'
				<input type="radio" name="enabled" value="0" '.(!$enabled ? 'checked="checked"' : '').' /> '.$this->l('No').'
			</div>
			<label>'.$this->l('Test flag').'</label>
			<div class="margin-form">
				<input type="radio" name="testflag" value="1" '.($testflag ? 'checked="checked"' : '').' /> '.$this->l('Yes').'
				<input type="radio" name="testflag" value="0" '.(!$testflag ? 'checked="checked"' : '').' /> '.$this->l('No').'
			</div>
			<label>'.$this->l('Merchant ID').'</label>
			<div class="margin-form"><input type="text" size="10" name="merchantid" value="'.htmlentities($merchantid, ENT_COMPAT, 'UTF-8').'" /></div>
			<label>'.$this->l('Shared secret').'</label>
			<div class="margin-form"><input type="text" size="33" name="secret" value="'.htmlentities($secret, ENT_COMPAT, 'UTF-8').'" /></div>
			<label>'.$this->l('Pre-populate Person Nr').'</label>
			<div class="margin-form">
				<input type="radio" name="prepopulate" value="1" '.($prepopulate ? 'checked="checked"' : '').' /> '.$this->l('Yes').'
				<input type="radio" name="prepopulate" value="0" '.(!$prepopulate ? 'checked="checked"' : '').' /> '.$this->l('No').'
			</div>
			<label style="width: 200px; text-align: left;">'.$this->l('Countries').'</label>
			<div class="margin-form">
				<input type="checkbox" name="countries[]" value="SE" '.(strstr($countries, "SE") ? 'checked="checked"' : '').' /> '.$this->l('Sweden').'
				<input type="checkbox" name="countries[]" value="FI" '.(strstr($countries, "FI") ? 'checked="checked"' : '').' /> '.$this->l('Finland').'
				<input type="checkbox" name="countries[]" value="NO" '.(strstr($countries, "NO") ? 'checked="checked"' : '').' /> '.$this->l('Norway').'
				<input type="checkbox" name="countries[]" value="DK" '.(strstr($countries, "DK") ? 'checked="checked"' : '').' /> '.$this->l('Denmark').'
				<input type="checkbox" name="countries[]" value="DE" '.(strstr($countries, "DE") ? 'checked="checked"' : '').' /> '.$this->l('Germany').'
				<input type="checkbox" name="countries[]" value="NL" '.(strstr($countries, "NL") ? 'checked="checked"' : '').' /> '.$this->l('Netherland').'
			</div>
			<label>'.$this->l('Credit limit').'</label>
			<div class="margin-form"><input type="text" size="10" name="orderlimit" value="'.htmlentities($orderlimit, ENT_COMPAT, 'UTF-8').'" /></div>
			<br /><center><input type="submit" name="submitKreditor" value="'.$this->l('Update settings').'" class="button" /></center>
		<fieldset class="width3">
			<legend><img src="../img/admin/warning.gif" />'.$this->l('Information').'</legend>
			<b style="color: red;">'.$this->l('All PrestaShop currencies must be configured</b> inside Payment  > Currencies').'<br />
		</fieldset>';
	}

	public function hookPayment($params)
	{
		global $smarty;

		$errors 	= "";
		$address 	= new Address(intval($params['cart']->id_address_invoice));
		$country = new Country($address->id_country);
		$customer 	= new Customer(intval($params['cart']->id_customer));
		$currency 	= $this->getCurrency();
		
		$ordertotal = Tools::convertPrice($params['cart']->getOrderTotal(true, 3), $currency);
		
		/*
		 * Order value including the invoice fee may NOT excede the credit limit.
		 */
		if (intval(Configuration::get('KREDITOR_PP_ENABLED')) != 1)
			return $this->l('Kreditor error: (Kreditor not enabled)');	
		
		if ($ordertotal>Tools::convertPrice(floatval(Configuration::get('KREDITOR_PP_ORDER_LIMIT')), $currency))
			return $this->l('Kreditor error: (Order value exceeds the credit limit)');	
		
		if (!Validate::isLoadedObject($address) OR !Validate::isLoadedObject($customer) OR !Validate::isLoadedObject($currency))
			return $this->l('Kreditor error: (invalid address or customer)');
		
		if (!((strcasecmp($currency->iso_code, "SEK") == 0 && strpos(Configuration::get('KREDITOR_PP_COUNTRIES'), 'SE') !== false && $country->iso_code == "SE") || (strcasecmp($currency->iso_code, "EUR") == 0 && strpos(Configuration::get('KREDITOR_PP_COUNTRIES'), 'FI') !== false && $country->iso_code == "FI") || (strcasecmp($currency->iso_code, "EUR") == 0 && strpos(Configuration::get('KREDITOR_PP_COUNTRIES'), 'DE') !== false && $country->iso_code == "DE") || (strcasecmp($currency->iso_code, "DKK") == 0 && strpos(Configuration::get('KREDITOR_PP_COUNTRIES'), 'DK') !== false && $country->iso_code == "DK") || (strcasecmp($currency->iso_code, "NOK") == 0 && strpos(Configuration::get('KREDITOR_PP_COUNTRIES'), 'NO') !== false && $country->iso_code == "NO") || (strcasecmp($currency->iso_code, "EUR") == 0 && strpos(Configuration::get('KREDITOR_PP_COUNTRIES'), 'NL') !== false && $country->iso_code == "NL"))) {
			//return $this->l('Kreditor error: (unsupported currency)');
			// Only SEK valid, no error is displayed.
			return "";
		}
		
	
		if ($params['cart']->id_address_invoice != $params['cart']->id_address_delivery) {
			$errors .= $this->l('The invoice and delivery address must be the same when using kreditor. The delivery address will be changed to be the same as the invoice address.');
		}
			
		$products = $params['cart']->getProducts();
		
		foreach ($products as $key => $product)
		{
			$products[$key]['name'] = str_replace('"', '\'', $product['name']);
			if (isset($product['attributes']))
				$products[$key]['attributes'] = str_replace('"', '\'', $product['attributes']);
			$products[$key]['name'] = htmlentities(utf8_decode($product['name']));
			$products[$key]['KreditorAmount'] = number_format(Tools::convertPrice($product['price_wt'], $currency), 2, '.', '');
		}
		$pno = "";
		if (Configuration::get('KREDITOR_PP_PRE_POPULATE') == 1) {
			$pno = date("ymd", strtotime($customer->birthday));
		}
		
		$smarty->assign(array(
			'address' => $address,
			'country' => new Country(intval($address->id_country)),
			'customer' => $customer,
			'currency' => $currency,
			'pno' => $pno,
			'telephone' => $address->phone,
			'email' => $customer->email,
			'amount' => number_format(Tools::convertPrice($params['cart']->getOrderTotal(true, 4), $currency), 2, '.', ''),
			'shipping' =>  number_format((Tools::convertPrice(($params['cart']->getOrderShippingCost() + $params['cart']->getOrderTotal(true, 6)), $currency)), 2, '.', ''),
			'discounts' => $params['cart']->getDiscounts(),
			'products' => $products,
			'total' => number_format(Tools::convertPrice($params['cart']->getOrderTotal(true, 3), $currency), 2, '.', ''),
			'id_cart' => intval($params['cart']->id),
			'this_path' => $this->_path,
		    'this_path_ssl' => (Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://').htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8').__PS_BASE_URI__.'modules/'.$this->name.'/',
			'kreditorerrors' => $errors
		));

		return $this->display(__FILE__, 'kreditorpartpayment.tpl');
    }
    
    function validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod = 'Unknown', $message = NULL, $extraVars = array(), $currency_special = NULL)
	{
		$cart = new Cart(intval($id_cart));

		/* Does order already exists ? */
		if (Validate::isLoadedObject($cart) AND $cart->OrderExists() == 0)
		{
			/* Copying data from cart */
			$order = new Order();
			$order->id_carrier = intval($cart->id_carrier);
			$order->id_customer = intval($cart->id_customer);
			$order->id_address_invoice = intval($cart->id_address_invoice);
			$order->id_address_delivery = intval($cart->id_address_delivery);
			$vat_address = new Address(intval($order->id_address_delivery));
			$id_zone = Address::getZoneById(intval($vat_address->id));
			$order->id_currency = ($currency_special ? intval($currency_special) : intval($cart->id_currency));
			$order->id_lang = intval($cart->id_lang);
			$order->id_cart = intval($cart->id);
			$customer = new Customer(intval($order->id_customer));
			$order->secure_key = pSQL($customer->secure_key);
			$order->payment = substr($paymentMethod, 0, 32);
			if (isset($this->name))
				$order->module = $this->name;
			$order->total_paid_real = floatval(number_format($amountPaid, 2, '.', ''));
			$order->recyclable = $cart->recyclable;
			$order->gift = intval($cart->gift);
			$order->gift_message = $cart->gift_message;
			$currency = new Currency($order->id_currency);
			$amountPaid = floatval(Tools::convertPrice(floatval(number_format($amountPaid, 2, '.', '')), $currency))+floatval($invoicefee);
			$order->total_paid_real = $amountPaid;
			$order->total_products = floatval(Tools::convertPrice(floatval(number_format($cart->getOrderTotal(false, 1), 2, '.', '')), $currency));
			$order->total_products_wt = floatval(Tools::convertPrice(floatval(number_format($cart->getOrderTotal(true, 1), 2, '.', '')), $currency));
			$order->total_discounts = floatval(Tools::convertPrice(floatval(number_format(abs($cart->getOrderTotal(true, 2)), 2, '.', '')), $currency));
			$order->total_shipping = floatval(Tools::convertPrice(floatval(number_format($cart->getOrderShippingCost(), 2, '.', '')), $currency))+floatval($invoicefee);
			$order->total_wrapping = floatval(Tools::convertPrice(floatval(number_format(abs($cart->getOrderTotal(true, 6)), 2, '.', '')), $currency));
			$order->total_paid = floatval(Tools::convertPrice(floatval(number_format($cart->getOrderTotal(true, 3), 2, '.', '')), $currency))+floatval($invoicefee);
			/* Amount paid by customer is not the right one -> Status = payment error */
			if ($order->total_paid != $order->total_paid_real)
				$id_order_state = _PS_OS_ERROR_;

			/* Creating order */
			$result = $order->add();

			/* Next ! */
			if ($result AND isset($order->id))
			{
				/* Set order state in order history */
				$history = new OrderHistory();
				$history->id_order = intval($order->id);
				$history->changeIdOrderState(intval($id_order_state), intval($order->id));
				$history->addWithemail(true, $extraVars);

				/* Optional message to attach to this order */
				if (isset($message) AND !empty($message))
				{
					$msg = new Message();
					$message = strip_tags($message, '<br>');
					if (!Validate::isMessage($message))
						$message = $this->l('Payment message is not valid, please check your module!');
					$msg->message = $message;
					$msg->id_order = intval($order->id);
					$msg->private = 1;
					$msg->add();
				}

				/* Insert products from cart into order_detail table */
				$products = $cart->getProducts();
				$productsList = '';
				$db = Db::getInstance();
				$query = 'INSERT INTO `'._DB_PREFIX_.'order_detail`
					(`id_order`, `product_id`, `product_attribute_id`, `product_name`, `product_quantity`, `product_price`, `product_quantity_discount`, `product_ean13`, `product_reference`, `product_supplier_reference`, `product_weight`, `tax_name`, `tax_rate`, `ecotax`, `download_deadline`, `download_hash`)
				VALUES ';

				$customizedDatas = Product::getAllCustomizedDatas(intval($order->id_cart));
				Product::addCustomizationPrice($products, $customizedDatas);
				foreach ($products AS $key => $product)
				{
					if ($id_order_state != _PS_OS_CANCELED_ AND $id_order_state != _PS_OS_ERROR_)
					{
						if (($id_order_state != _PS_OS_OUTOFSTOCK_) AND (($updateResult = Product::updateQuantity($product)) === false OR $updateResult === -1))
							{
								$id_order_state = _PS_OS_OUTOFSTOCK_;
								$history = new OrderHistory();
								$history->id_order = intval($order->id);
								$history->changeIdOrderState(_PS_OS_OUTOFSTOCK_, intval($order->id));
								$history->addWithemail();
							}
						Hook::updateQuantity($product, $order);
					}
					$price = Tools::convertPrice(Product::getPriceStatic(intval($product['id_product']), false, ($product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL), 4), $currency);
					$price_wt = Tools::convertPrice(Product::getPriceStatic(intval($product['id_product']), true, ($product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL), 4), $currency);

					/* Add some informations for virtual products */
					$deadline = '0000-00-00 00:00:00';
					$download_hash = NULL;
					$productDownload = new ProductDownload();
					if ($id_product_download = $productDownload->getIdFromIdProduct(intval($product['id_product'])))
					{
						$productDownload = new ProductDownload(intval($id_product_download));
						$deadline = $productDownload->getDeadLine();
						$download_hash = $productDownload->getHash();
					}

					/* Exclude VAT */
					if (Tax::excludeTaxeOption())
					{
						$product['tax'] = 0;
						$product['rate'] = 0;
					}
					else
						$tax = Tax::getApplicableTax(intval($product['id_tax']), floatval($product['rate']));

					/* Quantity discount */
					$reduc = 0.0;
					if ($product['quantity'] > 1 AND ($qtyD = QuantityDiscount::getDiscountFromQuantity($product['id_product'], $product['quantity'])))
					{
						$reduc = QuantityDiscount::getValue($price_wt, $qtyD->id_discount_type, $qtyD->value);
						$price -= $reduc / (1 + floatval($tax) / 100);
					}

					
					/* Backwards compatibility fix */
					if(isset($product['cart_quantity']))
					{
						$quantity = $product['cart_quantity'];
					}
					else
					{
						$quantity = $product['quantity'];
					}
					/* Query */			
					$query .= '('.intval($order->id).',
						'.intval($product['id_product']).',
						'.(isset($product['id_product_attribute']) ? intval($product['id_product_attribute']) : 'NULL').',
						\''.pSQL($product['name'].((isset($product['attributes']) AND $product['attributes'] != NULL) ? ' - '.$product['attributes'] : '')).'\',
						'.intval($quantity).',
						'.floatval($price).',
						'.floatval($reduc).',
						'.(empty($product['ean13']) ? 'NULL' : '\''.pSQL($product['ean13']).'\'').',
						'.(empty($product['reference']) ? 'NULL' : '\''.pSQL($product['reference']).'\'').',
						'.(empty($product['supplier_reference']) ? 'NULL' : '\''.pSQL($product['supplier_reference']).'\'').',
						'.floatval($product['weight']).',
						\''.(!$tax ? '' : pSQL($product['tax'])).'\',
						'.floatval($tax).',
						'.floatval($product['ecotax']).',
						\''.pSQL($deadline).'\',
						\''.pSQL($download_hash).'\'),';

					$priceWithTax = number_format($price * (($tax + 100) / 100), 2, '.', '');
					$customizationQuantity = 0;
					if (isset($customizedDatas[$product['id_product']][$product['id_product_attribute']]))
					{
						$customizationQuantity = intval($product['customizationQuantityTotal']);
						$productsList .=
						'<tr style="background-color:'.($key%2 ? '#DDE2E6' : '#EBECEE').';">
							<td style="padding:0.6em 0.4em;">'.$product['reference'].'</td>
							<td style="padding:0.6em 0.4em;"><strong>'.$product['name'].(isset($product['attributes_small']) ? ' '.$product['attributes_small'] : '').' - '.$this->l('Customized').'</strong></td>
							<td style="padding:0.6em 0.4em; text-align:right;">'.Tools::displayPrice($price * ($tax + 100) / 100, $currency, false, false).'</td>
							<td style="padding:0.6em 0.4em; text-align:center;">'.$customizationQuantity.'</td>
							<td style="padding:0.6em 0.4em; text-align:right;">'.Tools::displayPrice($customizationQuantity * $priceWithTax, $currency, false, false).'</td>
						</tr>';
					}

					if (!$customizationQuantity OR intval($product['quantity']) > $customizationQuantity)
						$productsList .=
						'<tr style="background-color:'.($key%2 ? '#DDE2E6' : '#EBECEE').';">
							<td style="padding:0.6em 0.4em;">'.$product['reference'].'</td>
							<td style="padding:0.6em 0.4em;"><strong>'.$product['name'].(isset($product['attributes_small']) ? ' '.$product['attributes_small'] : '').'</strong></td>
							<td style="padding:0.6em 0.4em; text-align:right;">'.Tools::displayPrice($price * ($tax + 100) / 100, $currency, false, false).'</td>
							<td style="padding:0.6em 0.4em; text-align:center;">'.(intval($product['quantity']) - $customizationQuantity).'</td>
							<td style="padding:0.6em 0.4em; text-align:right;">'.Tools::displayPrice((intval($product['quantity']) - $customizationQuantity) * $priceWithTax, $currency, false, false).'</td>
						</tr>';
				} /* end foreach ($products) */
				$query = rtrim($query, ',');
				$result = $db->Execute($query);

				/* Insert discounts from cart into order_discount table */
				$discounts = $cart->getDiscounts();
				$discountsList = '';
				foreach ($discounts AS $discount)
				{
					$objDiscount = new Discount(intval($discount['id_discount']));
					$value = $objDiscount->getValue(sizeof($discounts), $cart->getOrderTotal(true, 1), $order->total_shipping, $cart->id);
					$order->addDiscount($objDiscount->id, $objDiscount->name, $value);
					if ($id_order_state != _PS_OS_ERROR_ AND $id_order_state != _PS_OS_CANCELED_)
						$objDiscount->quantity = $objDiscount->quantity - 1;
					$objDiscount->update();

					$discountsList .=
					'<tr style="background-color:#EBECEE;">
							<td colspan="4" style="padding:0.6em 0.4em; text-align:right;">'.$this->l('Voucher code:').' '.$objDiscount->name.'</td>
							<td style="padding:0.6em 0.4em; text-align:right;">-'.Tools::displayPrice($value, $currency, false, false).'</td>
					</tr>';
				}

				/* Specify order id for message */
				$oldMessage = Message::getMessageByCartId(intval($cart->id));
				if ($oldMessage)
				{
					$message = new Message(intval($oldMessage['id_message']));
					$message->id_order = intval($order->id);
					$message->update();
				}

				/* Hook new order */
				$orderStatus = new OrderState(intval($id_order_state));
				if (Validate::isLoadedObject($orderStatus))
				{
					Hook::newOrder($cart, $order, $customer, $currency, $orderStatus);
					foreach ($cart->getProducts() as $product)
						if ($orderStatus->logable)
							ProductSale::addProductSale($product['id_product'], $product['quantity']);
				}
				/* Send an e-mail to customer */
				if ($id_order_state != _PS_OS_ERROR_ AND $id_order_state != _PS_OS_CANCELED_ AND $customer->id)
				{
					$invoice = new Address(intval($order->id_address_invoice));
					$delivery = new Address(intval($order->id_address_delivery));
					$carrier = new Carrier(intval($order->id_carrier));
					$delivery_state = $delivery->id_state ? new State(intval($delivery->id_state)) : false;
					$invoice_state = $invoice->id_state ? new State(intval($invoice->id_state)) : false;

					$data = array(
						'{firstname}' => $customer->firstname,
						'{lastname}' => $customer->lastname,
						'{email}' => $customer->email,
						'{delivery_firstname}' => $delivery->firstname,
						'{delivery_lastname}' => $delivery->lastname,
						'{delivery_address1}' => $delivery->address1,
						'{delivery_address2}' => $delivery->address2,
						'{delivery_city}' => $delivery->city,
						'{delivery_postal_code}' => $delivery->postcode,
						'{delivery_country}' => $delivery->country,
						'{delivery_state}' => $delivery->id_state ? $delivery_state->name : '',
						'{delivery_phone}' => $delivery->phone,
						'{invoice_firstname}' => $invoice->firstname,
						'{invoice_lastname}' => $invoice->lastname,
						'{invoice_address2}' => $invoice->address2,
						'{invoice_address1}' => $invoice->address1,
						'{invoice_city}' => $invoice->city,
						'{invoice_postal_code}' => $invoice->postcode,
						'{invoice_country}' => $invoice->country,
						'{invoice_state}' => $invoice->id_state ? $invoice_state->name : '',
						'{invoice_phone}' => $invoice->phone,
						'{order_name}' => sprintf("#%06d", intval($order->id)),
						'{date}' => Tools::displayDate(date('Y-m-d h:i:s'), intval($order->id_lang), 1),
						'{carrier}' => (strval($carrier->name) != '0' ? $carrier->name : Configuration::get('PS_SHOP_NAME')),
						'{payment}' => $order->payment,
						'{products}' => $productsList,
						'{discounts}' => $discountsList,
						'{total_paid}' => Tools::displayPrice($order->total_paid, $currency, false, false),
						'{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping+ $order->total_discounts, $currency, false, false),
						'{total_discounts}' => Tools::displayPrice($order->total_discounts, $currency, false, false),
						'{total_shipping}' => Tools::displayPrice($order->total_shipping, $currency, false, false),
						'{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $currency, false, false)
					);
					
					if (is_array($extraVars))
						$data = array_merge($data, $extraVars);

					/* Join PDF invoice */
					if (intval(Configuration::get('PS_INVOICE')) AND Validate::isLoadedObject($orderStatus) AND $orderStatus->invoice)
					{
						$fileAttachment['content'] = PDF::invoice($order, 'S');
						$fileAttachment['name'] = sprintf('FA%06d.pdf', intval($order->id));
						$fileAttachment['mime'] = 'application/pdf';
					}
					else
						$fileAttachment = NULL;

					if ($orderStatus->send_email AND Validate::isEmail($customer->email))
						Mail::Send(intval($order->id_lang), 'order_conf', 'Order confirmation', $data, $customer->email, $customer->firstname.' '.$customer->lastname, NULL, NULL, $fileAttachment);

					$this->currentOrder = intval($order->id);
					return true;
				}
				return true;
			}
			else
				die(Tools::displayError('Order creation failed'));
		}
		else
			die(Tools::displayError('An order has already been placed using this cart'));
	}
    
	
	public function getL($key)
	{
		$translations = array(
			'transaction' => $this->l('kreditor Invoice ID: '),
			'Shipping fee' => $this->l('Shipping fee'),
			'Wrong telephone' => $this->l('Wrong telephone'),
			'Wrong email' => $this->l('Wrong email'),
			'Gift wrapping fee' => $this->l('Gift wrapping fee'),
			'month' => $this->l('month'),
			'months' => $this->l('months'),
			'Account' => $this->l('Account')
		);
		return isset($translations[$key]) ? $translations[$key] : $this->l($key);
	}
}

?>
